import React, { useState, useEffect } from 'react';
import './index.less';
import { host } from '../utils/utils';
import {
    Table,
    Space,
    Button,
    Modal,
    Form,
    Input,
    Radio,
    Popconfirm,
    Select,
    Upload,
    message,
    Tag,
    Image,
} from 'antd';
import { FormOutlined, UploadOutlined } from '@ant-design/icons';
import { request } from 'umi';
const { Option } = Select;
const { TextArea } = Input;
const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
};
const tailLayout = {
    wrapperCol: { offset: 8, span: 16 },
};

const Index = () => {
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [listData, setListData] = useState([]);
    const [loading, setloading] = useState(false);
    const [saveId, setSaveId] = useState(0);
    const [pageData, setPageData] = useState({
        pageSize: 10,
        current: 1,
        total: 0,
    });
    const [form] = Form.useForm();

    const columns = [
        {
            title: '序号',
            dataIndex: 'id',
            key: 'id',
            width: 80,
        },
        {
            title: '关键字',
            dataIndex: 'keyword',
            key: 'keyword',
            width: 150,
        },
        {
            title: '回复内容',
            dataIndex: 'content',
            key: 'content',
            render: (text) => {
                return <pre>{text}</pre>;
            },
        },
        {
            title: '标签回复',
            key: 'tags',
            dataIndex: 'tags',
            width:150,
            render: (text) => {
                let tag = text ? text.split(',') : [];
                return <>{tag.map((item) => {
                    return <Tag style={{marginBottom:'8px'}} color="cyan">{item}</Tag>
                })}</>;
            },
        },
        {
            title: '触发次数',
            key: 'count',
            dataIndex: 'count',
            sorter: true,
        },
        {
            title: '图片',
            key: 'img',
            dataIndex: 'img',
            width: 410,
            render: (text, record) => {
                if (!text) {
                    return '';
                }
                let imgs = text.split(',');
                return (
                    <Image.PreviewGroup>
                        {imgs.map((item, key) => {
                            return (
                                <Image
                                    key={key}
                                    width={100}
                                    height={100}
                                    src={`${host}/storage/${item}`}
                                />
                            );
                        })}
                    </Image.PreviewGroup>
                );
            },
        },
        {
            title: '视频',
            key: 'video',
            dataIndex: 'video',
            width: 210,
            render: (text, record) => {
                if (!text) {
                    return '';
                }
                let videos = text.split(',');
                return (
                    <div>
                        {videos.map((item, key) => {
                            return (
                                <video
                                    key={key}
                                    width="200"
                                    height="112"
                                    style={{
                                        marginRight: '10px',
                                    }}
                                    controls
                                    src={`${host}/storage/${item}`}
                                />
                            );
                        })}
                    </div>
                );
            },
        },
        {
            title: '是否热门',
            key: 'hot',
            dataIndex: 'hot',
            render: (text) => {
                if (text == 1) {
                    return <Tag color="red">是</Tag>;
                } else {
                    return <Tag>否</Tag>;
                }
            },
        },
        {
            title: '是否欢迎',
            key: 'welcome',
            dataIndex: 'welcome',
            render: (text) => {
                if (text == 1) {
                    return <Tag color="red">是</Tag>;
                } else {
                    return <Tag>否</Tag>;
                }
            },
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <Space size="middle">
                    <a
                        onClick={() => {
                            setSaveId(record.id);
                            setIsModalVisible(true);
                            console.log(record);
                            let img = record.img.split(',');
                            let imgFileArr = [];
                            img.map((item) => {
                                imgFileArr.push({
                                    uid: item,
                                    name: item,
                                    status: 'done',
                                    response: {
                                        data: item,
                                    },
                                    url: `${host}/storage/${item}`,
                                });
                            });

                            let video = record.video.split(',');
                            let videoFileArr = [];
                            video.map((item) => {
                                videoFileArr.push({
                                    uid: item,
                                    name: item,
                                    status: 'done',
                                    response: {
                                        data: item,
                                    },
                                    url: `${host}/storage/${item}`,
                                });
                            });
                            form.setFieldsValue({
                                keyword: record.keyword,
                                content: record.content,
                                img: imgFileArr,
                                video: videoFileArr,
                                tags: record.tags && record.tags.split(','),
                            });
                        }}
                    >
                        修改
                    </a>
                    <a
                        onClick={() => {
                            request(`${host}/v1.0/api/key/save`, {
                                method: 'post',
                                data: {
                                    id: record.id,
                                    hot: 1,
                                },
                            }).then((res) => {
                                if (res.code == 200) {
                                    getList(pageData.current);
                                    message.success('成功!');
                                }
                            });
                        }}
                    >
                        设为热门
                    </a>
                    <a
                        onClick={() => {
                            request(`${host}/v1.0/api/key/save`, {
                                method: 'post',
                                data: {
                                    id: record.id,
                                    hot: 0,
                                },
                            }).then((res) => {
                                if (res.code == 200) {
                                    getList(pageData.current);
                                    message.success('成功!');
                                }
                            });
                        }}
                    >
                        取消热门
                    </a>
                    <a
                        onClick={() => {
                            request(`${host}/v1.0/api/key/save`, {
                                method: 'post',
                                data: {
                                    id: record.id,
                                    welcome: 1,
                                },
                            }).then((res) => {
                                if (res.code == 200) {
                                    getList(pageData.current);
                                    message.success('成功!');
                                }
                            });
                        }}
                    >
                        设为欢迎
                    </a>
                    <a
                        onClick={() => {
                            request(`${host}/v1.0/api/key/save`, {
                                method: 'post',
                                data: {
                                    id: record.id,
                                    welcome: 0,
                                },
                            }).then((res) => {
                                if (res.code == 200) {
                                    getList(pageData.current);
                                    message.success('成功!');
                                }
                            });
                        }}
                    >
                        取消欢迎
                    </a>
                    <Popconfirm
                        placement="bottomRight"
                        title={'确认删除？'}
                        onConfirm={() => {
                            setloading(true);
                            request(`${host}/v1.0/api/key/delete`, {
                                method: 'post',
                                data: {
                                    id: record.id,
                                },
                            }).then((res) => {
                                if (res.code == 200) {
                                    getList(pageData.current);
                                }
                            });
                        }}
                        okText="Yes"
                        cancelText="No"
                    >
                        <a style={{ color: 'red' }}>删除</a>
                    </Popconfirm>
                </Space>
            ),
        },
    ];

    const getList = (page) => {
        request(`${host}/v1.0/api/key/list`, {
            method: 'get',
            params: {
                page: page,
            },
        }).then((res) => {
            if (res.code == 200) {
                setListData(res.data.data);
                setPageData({
                    pageSize: 10,
                    current: res.data.current_page,
                    total: res.data.total,
                });
                setloading(false);
            }
        });
    };

    useEffect(() => {
        getList(1);
    }, []);

    const showModal = () => {
        setIsModalVisible(true);
        setSaveId(0);
        form.resetFields();
    };

    /**
     * 新建关键字
     */
    const handleOk = () => {
        setIsModalVisible(false);
        // 获取form的值
        console.log(form.getFieldsValue());
        let fromData = form.getFieldsValue();
        let img = [];
        let video = [];
        fromData.img &&
            fromData.img.map((item) => {
                img.push(item.response.data);
            });
        fromData.video &&
            fromData.video.map((item) => {
                video.push(item.response.data);
            });

        let data = {
            keyword: fromData.keyword,
            img: img.join(','),
            video: video.join(','),
            tags: fromData.tags ? fromData.tags.join(',') : '',
            content: fromData.content,
        };

        if (saveId > 0) {
            data.id = saveId;
        }

        request(`${host}/v1.0/api/key/save`, {
            method: 'post',
            data: data,
        }).then((res) => {
            if (res.code == 200) {
                getList(pageData.current);
                message.success('成功!');
            }
        });
    };

    const handleCancel = () => {
        setIsModalVisible(false);
    };
    const props = {
        name: 'file',
        action: `${host}/v1.0/api/key/upload`,
        onChange(info) {
            // console.log(info);
            if (info.file.status !== 'uploading') {
                // console.log(info.file, info.fileList);
            }
            if (info.file.status === 'done') {
                // message.success(`${info.file.name} file uploaded successfully`);
            } else if (info.file.status === 'error') {
                message.error(`${info.file.name} file upload failed.`);
            }
        },
        multiple: true,
    };

    const normFile = (e) => {
        console.log('Upload event:', e);
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    };

    return (
        <div className="Index">
            <div className="btnGroup">
                <Button
                    type="primary"
                    onClick={showModal}
                    icon={<FormOutlined />}
                >
                    新建关键字
                </Button>
            </div>
            <Table
                columns={columns}
                dataSource={listData}
                rowKey="id"
                loading={loading}
                onChange={(pagination, filters, sorter) => {
                    setloading(true);
                    request(`${host}/v1.0/api/key/list`, {
                        method: 'get',
                        params: {
                            page: pagination.current,
                            orderKey: sorter.field,
                            orderSort:
                                sorter.order == 'ascend' ? 'asc' : 'desc',
                        },
                    }).then((res) => {
                        if (res.code == 200) {
                            setListData(res.data.data);
                            setPageData({
                                pageSize: pageData.pageSize,
                                current: res.data.current_page,
                                total: res.data.total,
                            });
                            setloading(false);
                        }
                    });
                }}
                pagination={{
                    pageSize: pageData.pageSize,
                    current: pageData.current,
                    total: pageData.total,
                    showSizeChanger: false
                }}
            />
            <Modal
                title="关键字"
                visible={isModalVisible}
                onOk={handleOk}
                width={800}
                onCancel={handleCancel}
            >
                <Form {...layout} form={form}>
                    <Form.Item
                        label="关键字"
                        name="keyword"
                        rules={[{ required: true }]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="回复内容"
                        name="content"
                        rules={[{ required: true }]}
                    >
                        <TextArea rows="10" />
                    </Form.Item>
                    <Form.Item
                        label="标签回复"
                        name="tags"
                        rules={[{ required: true }]}
                    >
                        <Select
                            mode="tags"
                            style={{ width: '100%' }}
                            placeholder="Tags Mode"
                        ></Select>
                    </Form.Item>

                    <Form.Item
                        label="图片"
                        name="img"
                        valuePropName="fileList"
                        getValueFromEvent={normFile}
                    >
                        <Upload {...props} accept="image/*">
                            <Button icon={<UploadOutlined />}>点击上传</Button>
                        </Upload>
                    </Form.Item>
                    <Form.Item
                        label="视频"
                        name="video"
                        valuePropName="fileList"
                        getValueFromEvent={normFile}
                    >
                        <Upload {...props} accept="video/*">
                            <Button icon={<UploadOutlined />}>点击上传</Button>
                        </Upload>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default Index;
